<?php

use App\Site\Contract\SiteServiceInterface;
use App\Site\Dto\SiteInfoDto;
use Hyperf\Context\Context;

function set_current_site(SiteInfoDto $siteInfo): void
{
    Context::set('current_site_info', $siteInfo);
}

function get_current_site(): ?SiteInfoDto
{
    return Context::get('current_site_info');
}

function call_with_site(SiteInfoDto|int|string $site, callable $callable): mixed
{
    if (!$site instanceof SiteInfoDto) {
        $s = container()->get(SiteServiceInterface::class)->findBySiteId($site);
        if (!$s) {
            throw new Exception('site invalid');
        }
        $site = SiteInfoDto::from($s);
    }
    try {
        Context::set('temp_site_info', $site);
        return call_user_func_array($callable, []);
    } finally {
        Context::set('temp_site_info', null);
    }
}

function get_temp_site(): ?SiteInfoDto
{
    return Context::get('temp_site_info');
}

// 根据文件路径获取文件完整地址
function get_file_url(string $path): string
{
    // 目前只处理oss
    // todo 其他
    return env('OSS_SCHEMA') . env('OSS_DOMAIN') . $path;
}